/*
 * @Description:  观察者
 * @Author: YiHe
 * @Date: 2020-08-20 13:42:00
 * @LastEditors: YiHe
 * @LastEditTime: 2020-08-20 22:21:28
 */
import Dep from './dep.js'
class Observer {
	constructor(data) {
		Object.keys(data).forEach(key => {
			this.observeReactive(data, key, data[key])
		})
	}
	observeReactive(data, key, val) {
		observe(val)
		const dep = new Dep(key)
		Object.defineProperty(data, key, {
			get: function () {
				return val
			},
			set: (newVal) => {
				console.log(`${key}:${val}=>${newVal}`)
				val = newVal
				observe(newVal)
				dep.notify()
			}
		})
	}
}

function observe(data) {
	if (!data || typeof data !== 'object') return
	return new Observer(data)
}

export default observe